package com.itdd.service.impl;

import com.itdd.mapper.BookMapper;
import com.itdd.mapper.BorrowMapper;
import com.itdd.pojo.Book;
import com.itdd.pojo.Borrow;
import com.itdd.pojo.User;
import com.itdd.service.BorrowService;
import com.itdd.service.utils.GetSqlSession;
import org.apache.ibatis.session.SqlSession;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class BorrowServiceImpl implements BorrowService {
    @Override
    public void borrowBook(User user) {
        SqlSession sqlSession = GetSqlSession.getSqlSession();
        BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
        BorrowMapper borrowMapper = sqlSession.getMapper(BorrowMapper.class);
//定义一个输入
        Scanner Sca = new Scanner(System.in);
        while (true) {
            //一个全部书的集合
            List<Book> allBook = bookMapper.selectAll();
            System.out.println("书号\t书名\t\t\t\t书籍类型\t书籍余量");
            for (int i = 0; i < allBook.size(); i++) {
                System.out.println(allBook.get(i));
            }
            System.out.println("请输入你想借的书籍的书号");
            System.out.println("如果你想退出，请按0");
            int bId = Sca.nextInt();
            if (bId == 0) return;
//禁止同一个用户借同一本书俩次
            if (borrowMapper.selectBookByAcc(user.getUserAccount(), bId)) {
                System.out.println("你已经借过这本书了!");
                break;
            }
//借书的日期
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
            Date date = new Date(System.currentTimeMillis());
//将借的书号，借书者，借书日期添加到borrow数据库中
            borrowMapper.addBorrow(bId, user.getUserAccount(), formatter.format(date));
//借书后书的数量减一
            bookMapper.updateBookNum(bId);
        }
        sqlSession.close();
    }


    @Override
    public void displayBorrow() {
        SqlSession sqlSession = GetSqlSession.getSqlSession();
        BorrowMapper borrowMapper = sqlSession.getMapper(BorrowMapper.class);
//定义一个输入
        Scanner Sca = new Scanner(System.in);
        do {
//全部借书信息
            List<Borrow> allBorrow = borrowMapper.selectAllBorrow();
            System.out.println("这是全部的借书记录:");
            for (int i = 0; i < allBorrow.size(); i++) {
                System.out.println(allBorrow.get(i));
            }
            System.out.println("请输入你要删除的对应借书记录的书号和用户名\n想退出按0");
            borrowMapper.deleteByBookIdUserAcc(Sca.nextInt(), Sca.nextInt());
            System.out.println("删除成功！");
        } while (Sca.nextInt() != 0);
        sqlSession.close();
    }

}
